import React, { useState, useEffect } from 'react';
import styles from './index.less';
import cls from 'classnames';
import { connect } from 'umi';
import { getEquipmentsByProjId } from '@/services/modelManageService';
import NoData from '../../noData';
import _ from 'lodash';

const DeviceInfo = ({ curProjId }) => {
  const [allNumber, setAllNumber] = useState(0);
  const [equipmentList, setEquipmentList] = useState([]);

  useEffect(() => {
    if (!curProjId) return;
    _getEquipmentsByProjId(curProjId);
  }, [curProjId]);

  async function _getEquipmentsByProjId(id) {
    const { data } = await getEquipmentsByProjId(id);
    if (data) {
      const res = data.data;
      if (Array.isArray(res)) {
        setEquipmentList(res);
        const sum = _.sumBy(res, item => {
          return item.totalNumber;
        });
        setAllNumber(sum);
      } else {
        setEquipmentList([]);
      }
    }
  }

  const renderItem = () => {
    return equipmentList.map(item => {
      const all = item.totalNumber;
      return (
        <div className={cls(styles.deviceStateItemWrap)} key={item.equipmentName}>
          <div className={cls(styles.deviceStateItem)}>
            <div className={cls(styles.deviceStateTitle)}>
              <a href={item.linkUrl} target="_blank" rel="noreferrer" className={styles.name}>
                {item.equipmentName}
              </a>
              {/* <div className={styles.nameNumber}>{all}</div> */}
            </div>
            <div className={cls(styles.deviceStateContent)}>
              <div>
                <span className={cls(styles.deviceStateContentName)}>进场</span>
                <span className={cls(styles.deviceStateContentValue)}> {item.enterNumber}</span>
              </div>
              <div>
                <span className={cls(styles.deviceStateContentName)}>离场</span>
                <span className={cls(styles.deviceStateContentValue1)}>{item.leaveNumber}</span>
              </div>
            </div>

            <div className={cls(styles.deviceChart)}>
              <div
                className={cls(styles.deviceChartL)}
                style={{ width: (item.enterNumber / all) * 100 + '%' }}
              ></div>
              <div
                className={cls(styles.deviceChartR)}
                style={{ width: (item.leaveNumber / all) * 100 + '%' }}
              ></div>
            </div>
          </div>
        </div>
      );
    });
  };

  return (
    <div className={cls(styles.deviceInfo)}>
      <div className={styles.title}>
        <div>工区设备信息</div>
        <div className={styles.all}>全部：{allNumber}</div>
      </div>

      <div className={cls(styles.deviceStateWrap)}>
        {equipmentList.length > 0 ? renderItem() : <NoData />}
      </div>
    </div>
  );
};

// export default DeviceInfo;
export default connect(({ app }) => {
  return { curProjId: app.curProjId };
})(DeviceInfo);
